package com.zrx.app.android.modules;

import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.ZRXUTIL;
import com.zrx.app.android.activity.BaseActivity;
import com.zrx.app.android.fragment.ItemFrag;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * Created by liuji on 2017/5/23.
 *
 *
 * 左边的label  包含了label名称，姓名，状态，备注
 */

public abstract class BaseModuleActivity extends BaseActivity {
    TextView label_name, label_state, label_comment,label_module_name;
    LinearLayout catalog;
    Button firstBtn=null;

    String rootPath,modulePath;
    JSONObject savedJson;

    abstract JSONObject getTemplate();
    abstract void fillData(JSONObject data);
    abstract String getModuleKey();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        label_module_name=(TextView) findViewById(R.id.label_module_name);
        label_name = (TextView) findViewById(R.id.label_name);
        label_state = (TextView) findViewById(R.id.label_state);
        label_comment = (TextView) findViewById(R.id.label_comment);
        catalog=(LinearLayout)findViewById(R.id.VIEW_CATALOG);    //catalog表示目录

        JSONObject rawRecord= JSON.parseObject(getIntent().getStringExtra("record"));

        if (rawRecord.containsKey("basicData") && rawRecord.getJSONObject("basicData").containsKey("融资人")) {  //containsKey判断是否含有键名
            label_name.setText("姓名:" + rawRecord.getJSONObject("basicData").getString("融资人"));//有这个键名并且还有融资人这个键值对
        } else
            label_name.setText("姓名:未知");

        if (rawRecord.containsKey("state")) {
            label_state.setText("状态:" + ZRXUTIL.translateState(rawRecord.getString("state")));
        } else
            label_state.setText("状态:未知");

        if (rawRecord.containsKey("comment")) {
            label_comment.setText("备注:" + rawRecord.getString("comment"));
        } else {
            label_comment.setText("备注:无");
        }

        rootPath=ZRXUTIL.getPath()+"/"+rawRecord.getString("id");
        modulePath=rootPath+"/"+getModuleName();

        File moduleDir=new File(modulePath);
        if(!moduleDir.exists())
            moduleDir.mkdirs();

        File savedFile=new File(rootPath,"obj.json");

        if(savedFile.exists()){
            String str=ZRXUTIL.getStringFromFile(savedFile.getAbsolutePath());
            savedJson=JSON.parseObject(str);
            savedJson.put("rawRecord",rawRecord);
        }else {
            savedJson = new JSONObject();

            savedJson.put("rawRecord",rawRecord);
        }

        final BaseModuleActivity self = this;
        if(savedJson.containsKey("editable")&&savedJson.getBoolean("editable").equals(false)){
            AlertDialog.Builder ad=new AlertDialog.Builder(this);
            ad.setMessage("此记录状态不可编辑");
            ad.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    self.finish();
                }
            });
            ad.create().show();
        }




        if(!savedJson.containsKey(getModuleKey())){
            savedJson.put(getModuleKey(),getTemplate());
        }

        fillData(savedJson);
        save(savedJson,rootPath+"/obj.json");

        JSONObject data = savedJson.getJSONObject(getModuleKey());

        LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        Set<String> keySet = data.keySet();
        List<String> orderedList = ZRXUTIL.sortByOrder(keySet, data);
        for(String title:orderedList){
            if(!(data.get(title) instanceof JSONObject))
                continue;
            JSONObject _item= (JSONObject) data.get(title);

            Button btn = (Button) inflater.inflate(R.layout.button, catalog, false);
            if(firstBtn==null)
                firstBtn=btn;
            btn.setText(title);

            catalog.addView(btn);
            final ItemFrag f1 = new ItemFrag(_item,savedJson,title,modulePath,rootPath+"/obj.json");//title, _item, tar);


            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    FragmentManager fragMan = getFragmentManager();
                    FragmentTransaction fragTransaction = fragMan.beginTransaction();
                    fragTransaction.replace(R.id.content, f1);
                    fragTransaction.commit();
                }
            });

        }

        firstBtn.performClick();
    }



    void save(JSONObject savedJson,String path){
        save(savedJson,path,false);
    }
    void save(JSONObject savedJson,String path,boolean forced){
        if(savedJson.containsKey("editable")&& (Boolean.FALSE.equals(savedJson.getBoolean("editable"))&&!forced))
            return;

        File file = new File(path);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(savedJson.toJSONString().getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void updateEle(JSONObject tar, String key, Object val, String id, boolean editable) {//更新元素
        String tarType = tar.getString("type");
        if (tar.containsKey("val") && !"".equals(tar.get("val"))) {
            String tarVal = tar.getString("val");
            if (tarType.equals("字段")) {
                tar.put("rawVal", val);
            } else if (tarType.equals("照片") && tarVal != null && !tarVal.equals(val)) {
                new File(ZRXUTIL.getPhotoFile(id, key)).delete();
                new File(ZRXUTIL.getRawPhotoFile(id, key)).delete();
                tar.put("val", val);
            } else if (tarType.equals("视频") && tarVal != null && !tarVal.equals(val)) {
                new File(ZRXUTIL.getVideoFile(id, key)).delete();
                new File(ZRXUTIL.getRawVideoFile(id, key)).delete();
                tar.put("val", val);
            }
        } else
            tar.put("val", val);
        tar.put("editable", editable);
    }
}
